﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using TaxAssistantBase;
using System.Threading;
using BillHelper;
using System.Management;
using System.IO.Pipes;
using ShiBieProject;
using static ShiBieProject.updateTime;
using System.Runtime.InteropServices;
using System.Text;

namespace DemoForBillOcr
{

    public partial class ShiBie : Form
    {
        [DllImport("opencvProcessingDLLSet.dll", EntryPoint = "GetQrCodeInfoInAndOut")]
        public static extern int GetQrCodeInfoInAndOut(ref byte input, ref byte output);
        [DllImport("opencvProcessingDLLSet.dll", EntryPoint = "imgProcessOverlap")]
        public static extern int imgProcessOverlap(ref byte input, ref byte output);
        [DllImport("opencvProcessingDLLSet.dll", EntryPoint = "qrcodeFind")]
        public static extern int qrcodeFind(ref byte input, ref byte output);
        private List<InvoiiceOcrModel> idIOMList = new List<InvoiiceOcrModel>();
        private List<HighSpeedRailTicket> iocrtgt = new List<HighSpeedRailTicket>();
        private List<InvoiceSonModel> idIOMSonList = new List<InvoiceSonModel>();
        private List<invoiceOcrDetailedModel> idIOMDetdList = new List<invoiceOcrDetailedModel>();
        private List<InvoiceSonModel> daiKaiList = new List<InvoiceSonModel>();
        private AutomationBillOcr billOcr = new AutomationBillOcr();
        private string PiaoJuUploadeAddress = "";
        private WsdLogger ocrlog = new WsdLogger("OcrLog");
        private WsdLogger updatelodelog = new WsdLogger("ShangChaunLog");
        private string batchid = "";
        private string todayTime = "";
        private DateTime oldOneTime = DateTime.Now.AddDays(-1);
        private string companyNameDB;
        InvoiceOcrTool invoiceOcrTool;
        public ShiBie()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;

        }
        //管道发送
        public static void WaitData(string currentValue)
        {
            try
            {
                NamedPipeClientStreamTool.Write(currentValue);
            }
            catch (Exception e)
            {
                WsdLogger.yxlog("error", "管道发送出错+ " + e.Message);
            }
        }
        public ShiBie(string[] batchids)
        {
            if (batchids.Length > 1)
            {
                batchid = batchids[0];//202002251703281896
                todayTime = batchids[1];
            }
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        //程序开始
        private void Form2_Load(object sender, EventArgs e)
        {
            Hide();
            Control.CheckForIllegalCrossThreadCalls = false;
            bool b = true;
            try
            {

                b = initForm();
                ocrlog.Write("初始化成功");
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "初始化错误" + ex.Message);
                Thread.Sleep(20 * 1000);
                return;
            }
            if (b)
            {
                try
                {
                    DealImgOrc();
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "处理识别" + ex.Message + "批次号为：" + batchid);
                    Close();
                }
            }
            else
            {
                Close();
            }
        }
        //修改系统时间
        public bool setSystemTime(DateTime dateTime)
        {
            // 授权成功
            SYSTEMTIME sysTime = DateTime2SystemTime(dateTime);
            bool success = SetLocalTime(ref sysTime);
            return success;
        }
        //修改系统时间所需要的参数
        public SYSTEMTIME DateTime2SystemTime(DateTime dateTime)
        {
            SYSTEMTIME sysTime = new SYSTEMTIME();
            sysTime.wYear = Convert.ToUInt16(dateTime.Year);
            sysTime.wMonth = Convert.ToUInt16(dateTime.Month);
            sysTime.wDay = Convert.ToUInt16(dateTime.Day);
            sysTime.wHour = Convert.ToUInt16(dateTime.Hour);
            sysTime.wMinute = Convert.ToUInt16(dateTime.Minute);
            sysTime.wSecond = Convert.ToUInt16(dateTime.Second);
            sysTime.wMilliseconds = Convert.ToUInt16(dateTime.Millisecond);
            return sysTime;
        }


        //初始化
        public bool initForm()
        {
            string strUserID = "2B2ADEFE5CB6650E2D9A";
            int recode = -1;
            try
            {
                ocrlog.Write("开始初始化");
                recode = billOcr.InitForm(strUserID);
                // MessageBox.Show("初始化成功recode" + recode);
                ocrlog.Write("初始化recode=" + recode);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "开始初始化A报错" + ex.Message);
                return false;
            }
            if (0 != recode)
            {
                int nErroLength;
                char[] erroBuffer = new char[256];
                try
                {
                    billOcr.GetErroInformation(recode, erroBuffer, out nErroLength);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "开始初始化B错误" + ex.Message);
                    return false;
                }
                Thread.Sleep(6 * 1000);
                return initForm();

            }
            var url = AppDomain.CurrentDomain.BaseDirectory;
            string newPath = Path.Combine(url, "mod\\modlist.mod");
            if (newPath != null)
            {
                m_strUsMod.Text = newPath;
                string path = newPath;
                LoadingMB(path);
                btn_selectPath_Click();
            }
            return true;
        }
        //加载模板
        private void LoadingMB(string path)
        {
            AutomationBillOcr billOcr = new AutomationBillOcr();
            List<int> modID = new List<int>();
            int recode = -1;
            modID.Add(ModelEnum.CUSTOM);//加载在定义票种
            try
            {
                recode = billOcr.LoadTemplate(path.ToString());
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板A错误" + ex.Message);
                return;
            }
            if (0 != recode)
            {
                int nErroLength;
                char[] erroBuffer = new char[256];
                try
                {
                    billOcr.GetErroInformation(recode, erroBuffer, out nErroLength);
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "加载模板B错误" + ex.Message);
                    return;
                }
                string errInfo = new string(erroBuffer);
                return;
            }
            modID.Add(ModelEnum.JDCFP);
            modID.Add(ModelEnum.TRAIN);
            modID.Add(ModelEnum.ZZS_INVOICE);
            modID.Add(ModelEnum.FLY);
            int[] selectedMod = new int[modID.Count];
            int i = 0;
            for (i = 0; i < modID.Count; i++)
            {
                selectedMod[i] = modID[i];
            }
            int reCode = -1;
            try
            {
                reCode = billOcr.SetFormTypes(selectedMod, modID.Count);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板C错误" + ex.Message);
                return;
            }
            modID.Clear();
            if (0 != reCode)
            {
                return;
            }
        }
        private IList<string> GetBatchInfoDicForDir()
        {
            var dd = AppDomain.CurrentDomain.BaseDirectory;
            string activeDir = dd;
            var newPath = Path.Combine(activeDir, "HandleWenJ\\" + todayTime + "\\" + batchid);
            if (!Directory.Exists(newPath))
            {
                return new List<string>();
            }
            DirectoryInfo dirInfo = new DirectoryInfo(newPath);
            IList<string> dic = new List<string>();
            foreach (var fileInfo in dirInfo.GetFiles())
            {
                if (fileInfo.Extension != ".txt")
                {
                    dic.Add(fileInfo.FullName);
                }
            }
            return dic;
        }
        int numcishu = 0;
        private void DealImgOrc()
        {
            string apiurl = ApiUrlList.DATALL;
            int mubantype = -1;
            IList<string> currentBatchidImgAddress = new List<string>();
            //获取当前批次下的图片地址
            try
            {
                currentBatchidImgAddress = GetBatchInfoDicForDir();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "获取当前批次下的图片地址报错" + ex.Message);
            }

            if (currentBatchidImgAddress.Count > 0)
            {
                int Total = currentBatchidImgAddress.Count;//总数
                int prossNumber = 0;//处理数
                for (int i = 0; i < currentBatchidImgAddress.Count; i++)
                {
                    try
                    {
                        prossNumber++;
                        var first = currentBatchidImgAddress[i];
                        ocrlog.Write("处理图片" + first + "总图片数" + currentBatchidImgAddress.Count);
                        string imgUrl = first;
                        string imgYSUrl = first;
                        var arr = imgUrl.Split('_');
                        if (arr.Length < 2)
                        {
                            WsdLogger.yxlog("error", "格式不正确");
                            return;
                        }
                        if (imgUrl == null)
                        {
                            imgUrl = "";
                        }
                        if (!string.IsNullOrEmpty(imgUrl))
                        {
                            if (File.Exists(imgUrl))
                            {
                                var recode = -1;
                                string tpresult = "";
                                string qrCodeValue = "";
                                string input = imgUrl;
                                int colorValue = 0;
                                try
                                {
                                    numcishu++;
                                    try
                                    {
                                        qrCodeValue = getQrCodeInfo(input);//获取二维码信息
                                    }
                                    catch (Exception ex) {
                                        WsdLogger.yxlog("error", "识别二维码报错" + ex.Message);
                                    }
                                    try
                                    {
                                        colorValue = invoiceOverlying(imgUrl, input, colorValue);//票据叠加
                                    }
                                    catch (Exception ex)
                                    {
                                        WsdLogger.yxlog("error", "识别报错" + ex.Message);
                                        errorUploadeImg(imgUrl);

                                    }

                                    recode = RecognizeLoadedImg(imgUrl, out tpresult, out mubantype);
                                    Console.WriteLine("处理到：" + imgUrl);
                                    if (recode == 34)
                                    {
                                        //先停止两秒
                                        Thread.Sleep(2 * 1000);
                                        recode = RecognizeLoadedImg(imgUrl, out tpresult, out mubantype);
                                        if (recode == 34)
                                        {
                                            huiFuMAxXZ(imgUrl, out recode, out tpresult, out mubantype);
                                        }
                                        string currentTime = DateTime.Now.ToString("yyyyMMdd");
                                        if (currentTime != todayTime)
                                        {
                                            SetCurremtShiJ();//设置时间
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "识别报错" + ex.Message);
                                    errorUploadeImg(imgUrl);
                                    continue;
                                }
                                try
                                {
                                    string[] imgUrlName = imgUrl.Split('\\');
                                    string tuPianUrl = "/piaojuNew/" + DeclareDateTool.currentDeclareDae.Substring(0, 4) + "/" + DeclareDateTool.currentDeclareDae.Substring(4, 2) + "/" + imgUrlName[imgUrlName.Length - 1];
                                    PiaoJuUploadeAddress = tuPianUrl;
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "得到图片地址报错" + ex.Message);
                                    continue;
                                }
                                InvoiiceOcrModel iom = new InvoiiceOcrModel();
                                HighSpeedRailTicket iotb = new HighSpeedRailTicket();
                                if (mubantype == ModelEnum.TRAIN)
                                {
                                    try
                                    {
                                        iotb = chuliGTBillTable(tpresult, imgUrl);
                                    }
                                    catch (Exception ex)
                                    {
                                        WsdLogger.yxlog("error", "处理统计表数据失败" + ex.Message);
                                        continue;
                                    }
                                    if (iotb != null)
                                    {
                                            iocrtgt.Add(iotb); 
                                    }
                                }

                                try
                                {
                                    if (idIOMSonList == null)
                                    {
                                        idIOMSonList = new List<InvoiceSonModel>();
                                    }
                                    if (idIOMDetdList == null)
                                    {
                                        idIOMDetdList = new List<invoiceOcrDetailedModel>();
                                    }

                                    if (mubantype == ModelEnum.ZZS_INVOICE || mubantype == ModelEnum.DIANZI_INVOICE)
                                    {
                                        iom = getInvoiceInfo(mubantype, imgUrl, recode, tpresult, qrCodeValue);
                                    }else if (mubantype == ModelEnum.TRAIN)
                                    {
                                      
                                    }
                                    else if (recode != 0 && mubantype != 0)
                                    {
                                        iom = getInvoiceInfo(mubantype, imgUrl, recode, tpresult, qrCodeValue);
                                    }
                                    else {
                                        iom = getInvoiceInfo(mubantype, imgUrl, recode, tpresult, qrCodeValue);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "单次处理批次数据报错" + ex.Message + "图片地址为：" + imgUrl);
                                    continue;
                                }
                                try
                                {
                                    if (prossNumber >= 2 && prossNumber != Total)
                                    {
                                        sendMessage(Total, prossNumber, mubantype);//发送
                                    }
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "发送报错" + ex.Message);
                                    updatelodelog.Write("上传图片地址 ：" + imgUrl);
                                    uploadPic(imgUrl);//上传图片 
                                    updatelodelog.Write("上传图片成功");
                                    continue;
                                }

                                try
                                {
                                    updatelodelog.Write("上传图片地址 ：" + imgUrl);
                                    uploadPic(imgUrl);//上传图片 
                                    updatelodelog.Write("上传图片成功");
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "上传图片报错" + ex.Message);
                                    continue;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WsdLogger.yxlog("error", "第" + prossNumber + "条扫描处理错误" + ex.Message);
                        continue;
                    }

                }
                if (Total == prossNumber)//处理结束
                {
                    //获取四位随机数
                    Random rad = new Random();//实例化随机数产生器rad；
                    int suijiID = rad.Next(1000, 10000);//用rad生成大于等于1000，小于等于9999的随机数
                    if (iocrtgt != null)
                    {
                        string apiuelse = ApiUrlList.SAVETJTABLE;
                        if (iocrtgt.Count > 0) {
                            foreach (InvoiiceOcrModel iom in idIOMList)
                            {
                                iom.batchnumber =Convert.ToString(suijiID);
                            }
                            foreach (HighSpeedRailTicket iog in iocrtgt)
                            {
                                iog.invoiceId = suijiID;
                            }
                        }
                    }
                    //1.处理票据
                    invoiceOcrTool = new ShiBieProject.InvoiceOcrTool(batchid, idIOMList, idIOMSonList);
                    var b = false;
                    try
                    {
                        b = invoiceOcrTool.DealInvoice();
                    }
                    catch (Exception ex)
                    {
                        b = false;
                        WsdLogger.yxlog("error", "处理票据报错：" + ex.Message);
                    }

                    if (!b)
                    {
                        Hide();
                    }

                    //保存高铁票
                    if (iocrtgt != null)
                    {
                        string apiuelse = ApiUrlList.SaveTrainTickets;
                        try
                        {
                            if (iocrtgt.Count > 0)
                            {
                                WsdLogger.yxlog("error", "保存统计表" + iocrtgt.Count);
                                forwardingToserversetj(iocrtgt, apiuelse);
                            }
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "保存统计表报错" + ex.Message);
                        }
                    }
                    try
                    {
                        sendMessage(Total, prossNumber, mubantype);//发送
                        ocrlog.Write("处理OCR完成，批次为：" + batchid);
                        idIOMList = new List<InvoiiceOcrModel>();
                        idIOMSonList = new List<InvoiceSonModel>();
                        idIOMDetdList = new List<invoiceOcrDetailedModel>();
                        billOcr.UninitRecogForm();
                    }
                    catch (Exception ex)
                    {
                        WsdLogger.yxlog("error", "报错点3" + ex.Message);
                    }
                    Close();//关闭进程
                }
            }
            else
            {
                WsdLogger.yxlog("error", "没有复制图片");
                Close();//关闭进程
            }
        }

        /// <summary>
        /// 
        /// 解析识别字符串，获取票据信息
        /// </summary>
        /// <param name="mubantype"></param>
        /// <param name="imgUrl"></param>
        /// <param name="recode"></param>
        /// <param name="tpresult"></param>
        /// <param name="qrCodeValue"></param>
        /// <returns></returns>
        private InvoiiceOcrModel getInvoiceInfo(int mubantype, string imgUrl, int recode, string tpresult, string qrCodeValue)
        {
            InvoiiceOcrModel iom = chuliModelOne(tpresult, imgUrl, qrCodeValue, recode, mubantype, idIOMSonList, idIOMDetdList);
            if (iom != null)
            {
                //通过发票号获取发票信息
                iom = InvoiceNumCheck.getInvoiceInfo(iom);
                idIOMList.Add(iom);
            }

            return iom;
        }

        private static int invoiceOverlying(string imgUrl, string input, int colorValue)
        {
            byte[] byteInput = Encoding.ASCII.GetBytes(input);
            byte[] byteOutput = new byte[1024];
            //找二维码清晰度确定是否为清晰图片
            int q = qrcodeFind(ref byteInput[0], ref byteOutput[0]);//用字节数组接收动态库传过来的字符串
            string Value = System.Text.Encoding.UTF8.GetString(byteOutput, 0, byteOutput.Length).Trim(); //将字节数组转换为
            string[] number = Value.Split('/');
            if (number.Length > 0)
            {
                int.TryParse(number[0], out colorValue);
            }
            if (colorValue < 70000)
            {
                if (!string.IsNullOrEmpty(imgUrl))
                {
                    //将图片叠加
                    int t = imgProcessOverlap(ref byteInput[0], ref byteOutput[0]);//用字节数组接收动态库传过来的字符串
                }
            }

            return colorValue;
        }

        private static string getQrCodeInfo(string input)
        {
            string qrCodeValue;
            byte[] qrbyteInput = Encoding.ASCII.GetBytes(input);
            byte[] qrbyteOutput = new byte[1024];
            int qrResault = GetQrCodeInfoInAndOut(ref qrbyteInput[0], ref qrbyteOutput[0]);//用字节数组接收动态库传过来的字符串
            qrCodeValue = System.Text.Encoding.UTF8.GetString(qrbyteOutput, 0, qrbyteOutput.Length).Trim(); //将得到的二维码信息转化成字符串
            return qrCodeValue;
        }

        private void errorUploadeImg(string imgUrl)
        {
            string[] imgUrlName = imgUrl.Split('\\');
            string tuPianUrl = "/piaojuNew/" + DeclareDateTool.currentDeclareDae.Substring(0, 4) + "/" + DeclareDateTool.currentDeclareDae.Substring(4, 2) + "/" + imgUrlName[imgUrlName.Length - 1];
            PiaoJuUploadeAddress = tuPianUrl;
            updatelodelog.Write("上传图片地址 ：" + imgUrl);
             uploadPic(imgUrl);//上传图片 
            updatelodelog.Write("上传图片成功");
        }

        private void huiFuMAxXZ(string imgUrl, out int recode, out string tpresult, out int mubantype)
        {
            oldOneTime = DateTime.Now.AddDays(-1);
            setSystemTime(oldOneTime);
            recode = RecognizeLoadedImg(imgUrl, out tpresult, out mubantype);
            SetCurrentTime();
        }
        private bool SetCurrentTime()
        {
            SetCurremtShiJ();
            string currentTime = DateTime.Now.ToString("yyyyMMdd");
            if (currentTime != todayTime)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        private void SetCurremtShiJ()
        {
            string HouseTime = DateTime.Now.ToString("HHmmss");
            DateTime dt = DateTime.ParseExact(todayTime + " " + HouseTime, "yyyyMMdd HHmmss", System.Globalization.CultureInfo.CurrentCulture);
            setSystemTime(dt);
        }
        private void setPiaoJuData(InvoiiceOcrModel iom)
        {
            if (iom.invoiceOcrSonLists != null)
            {
                if (iom.invoiceOcrSonLists.Count > 0)
                {

                }
                else
                {
                    idIOMList.Add(iom);
                }
            }
            else
            {
                idIOMList.Add(iom);
            }
        }
        private void TestUploade()
        {
            string apiurl = ApiUrlList.DATALL;
            int mubantype = -1;
            IList<string> currentBatchidImgAddress = new List<string>();
            //获取当前批次下的图片地址
            try
            {
                currentBatchidImgAddress = GetBatchInfoDicForDir();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "报错点" + ex.Message);
            }
            if (currentBatchidImgAddress.Count > 0)
            {
                int Total = currentBatchidImgAddress.Count;//总数
                int prossNumber = 0;//处理数
                for (int i = 0; i < currentBatchidImgAddress.Count; i++)
                {
                    prossNumber++;
                    var first = currentBatchidImgAddress[i];
                    ocrlog.Write("处理图片" + first + "总图片数" + currentBatchidImgAddress.Count);
                    string imgUrl = first;
                    var arr = imgUrl.Split('_');
                    if (arr.Length < 2)
                    {
                        WsdLogger.yxlog("error", "格式不正确");
                        return;
                    }
                    if (imgUrl == null)
                    {
                        imgUrl = "";
                    }
                    if (File.Exists(imgUrl))
                    {

                        try
                        {
                            string[] imgUrlName = imgUrl.Split('\\');
                            string tuPianUrl = "/piaojuNew/" + DeclareDateTool.currentDeclareDae.Substring(0, 4) + "/" + DeclareDateTool.currentDeclareDae.Substring(4, 2) + "/" + imgUrlName[imgUrlName.Length - 1];
                            PiaoJuUploadeAddress = tuPianUrl;
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "得到图片地址报错" + ex.Message);
                        }
                        try
                        {
                            updatelodelog.Write("上传图片地址 ：" + imgUrl);
                            uploadPic(imgUrl);//上传图片 
                            updatelodelog.Write("上传图片成功");
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "上传图片报错" + ex.Message);
                        }
                    }
                }
                if (Total == prossNumber)
                {
                    if (idIOMList == null)
                    {
                        idIOMList = new List<InvoiiceOcrModel>();
                    }
                    Close();//关闭进程
                }
            }
        }
        private void TestDealImgOrc()
        {
            string apiurl = ApiUrlList.DATALL;
            IList<string> currentBatchidImgAddress = new List<string>();
            //获取当前批次下的图片地址
            try
            {
                currentBatchidImgAddress = GetBatchInfoDicForDir();
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "报错点" + ex.Message);
            }
            if (currentBatchidImgAddress.Count > 0)
            {
                int Total = currentBatchidImgAddress.Count;//总数
                int prossNumber = 0;//处理数
                for (int i = 0; i < currentBatchidImgAddress.Count; i++)
                {
                    prossNumber++;
                    var first = currentBatchidImgAddress[i];
                    ocrlog.Write("处理图片" + first + "总图片数" + currentBatchidImgAddress.Count);
                    string imgUrl = first;
                    var arr = imgUrl.Split('_');
                    if (arr.Length < 2)
                    {
                        WsdLogger.yxlog("error", imgUrl + "格式不正确");
                        return;
                    }
                    if (imgUrl == null)
                    {
                        imgUrl = "";
                    }
                    if (File.Exists(imgUrl))
                    {
                        var recode = -1;
                        string tpresult = "";
                        int mubantype = -1;
                        try
                        {
                            while (true)
                            {
                                numcishu++;
                                recode = RecognizeLoadedImg(imgUrl, out tpresult, out mubantype);
                                Console.WriteLine("识别次数" + numcishu + "识别结果recode：" + recode);
                                if (recode == 34)
                                {
                                    //先停止两秒
                                    Console.WriteLine("识别次数最大停滞开始修改时间。次数" + numcishu + "识别结果recode：" + recode);
                                    Thread.Sleep(2 * 1000);
                                    recode = RecognizeLoadedImg(imgUrl, out tpresult, out mubantype);
                                    if (recode == 34)
                                    {
                                        huiFuMAxXZ(imgUrl, out recode, out tpresult, out mubantype);
                                    }
                                    Console.WriteLine("修改时间结束识别结果recode：" + recode);
                                    string currentTime = DateTime.Now.ToString("yyyyMMdd");
                                    if (currentTime != todayTime)
                                    {
                                        SetCurremtShiJ();//设置时间
                                    }
                                }
                            }

                            //WsdLogger.yxlog("error", "recode：" + recode);
                        }
                        catch (Exception ex)
                        {
                            WsdLogger.yxlog("error", "识别报错" + ex.Message);
                            Hide();
                        }
                    }
                }

            }
        }



        private void sendMessage(int Totle, int chuliNum, int mubantype)
        {
            string companyName = "";
            if (chuliNum == 2)
            {
                invoiceOcrTool = new InvoiceOcrTool(batchid, idIOMList, idIOMSonList);
            }
            companyName = invoiceOcrTool.BatchCompanyName(chuliNum);// idIOMList[0].companyName;

            if (companyName == null || companyName == "")
            {
                companyName = "未识别公司";
            }
            string message = "1$$" + batchid + "$$" + companyName + "$$" + Totle + "$$" + chuliNum;
             WaitData(message); 
            ocrlog.Write("传送通知数据：" + message);
        }


        private void uploadPic(string fileUrl)
        {
            uploadPic1(fileUrl);
        }
        private void uploadPic1(object obj)
        {
            string imgname = obj as string;
            if (imgname != null)
            {
                var newPath = GetNewPath(imgname);
                string[] names = imgname.Split('\\');
                //上传图片
                string yuanchUrl = "/piaojuNew/" + DeclareDateTool.currentDeclareDae.Substring(0, 4) + "/" + DeclareDateTool.currentDeclareDae.Substring(4, 2) + "/" + names[names.Length - 1];
                PiaoJuUploadeAddress = yuanchUrl;
                try
                {
                    bool runimg = cos_dotnet_sdk.COSTool.UploadFileForPublic(yuanchUrl, newPath);
                    //  WsdLogger.yxlog("error", "上传成功" + yuanchUrl + "----" + Convert.ToString(runimg));
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "上传错误" + ex.Message);
                }

            }
        }
        //选择文件夹
        private void btn_selectPath_Click()
        {
            string volume = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf('\\'));
            string newPaths = volume + @"\ScanPicture\" + todayTime;
            if (!Directory.Exists(newPaths))
            {
                Directory.CreateDirectory(newPaths);
            }
            m_strImgPath.Text = newPaths;
        }
        private string GetNewPath(string fileUrl)
        {
            var dd = AppDomain.CurrentDomain.BaseDirectory;
            string activeDir = dd;
            string newPath = Path.Combine(activeDir, "HandleWenJ\\" + todayTime + "\\" + batchid);
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            newPath += "\\" + Path.GetFileName(fileUrl);
            return newPath;
        }
        //识别模板
        private int RecognizeLoadedImg(string strImgName, out string recogresult, out int mubantype)
        {
            int recode = -1;
            List<string> modelPathList = new List<string>();
            try
            {
                recode = billOcr.LoadImage(strImgName);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "识别模板错误" + ex.Message);
                Thread.Sleep(1000);
                recogresult = ex.Message;
                mubantype = -1;
                return recode;
            }
            recogresult = "";
            mubantype = -1;
            if (0 != recode)
            {
                return recode;
            }
            int mode;
            try
            {
                int nTemplateGrade = billOcr.GetTemplateGrade(m_strUsMod.Text, out mode);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "识别模板B错误" + ex.Message);
                Thread.Sleep(1000);
                return recode;
            }
            char[] cArrFieldName = new char[256];
            cArrFieldName.Initialize();
            int nFiledName = -1;
            try
            {
                nFiledName = billOcr.GetFieldNameEx(cArrFieldName);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "识别模板C错误" + ex.Message);
                Thread.Sleep(1000);
                return recode;
            }
            string temp = "";
            if (nFiledName == 0)
            {
                string strFieldName = new string(cArrFieldName);
                temp = strFieldName;
            }
            int nCells = -1;
            int nType = -1;
            try
            {
                modelPathList = OnLoad();
                recode = billOcr.RecognizeForm(out nCells, out nType);
                if (recode != 0)
                {
                    //    //重新加载模板
                    //    modelPathList = OnLoad();
                    //    for (int i = 0; i < modelPathList.Count; i++)
                    //    {
                    //        LoadingMB(modelPathList[i]);
                    //        recode = shuaxinModel(strImgName, out recogresult, out mubantype, out nCells, out nType);
                    //        if (recode == 0)
                    //        {
                    //            mubantype = nType;
                    //            break;
                    //        }
                    //        else {
                    mubantype = -1;
                    //        }

                    //    }
                }
                else
                {
                    mubantype = nType;
                }
                recogresult = GetRecogResult(nCells);
                billOcr.GetResultByTxt(strImgName);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板和刷新模板错误" + ex.Message);
                Thread.Sleep(1000);
                return recode;
            }
            if (0 != recode)
            {
                return recode;
            }
            return 0;
        }
        //加载新模板
        private int shuaxinModel(string strImgName, out string recogresult, out int mubantype, out int nCells, out int nType)
        {
            int recode = -1;
            try
            {
                recode = billOcr.LoadImage(strImgName);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "加载模板错误" + ex.Message);
                Thread.Sleep(1000);
                recogresult = ex.Message;
                mubantype = -1;
                nCells = -1;
                nType = -1;
                return recode;
            }
            recogresult = "";
            mubantype = -1;
            if (0 != recode)
            {
                nCells = -1;
                nType = -1;
                return recode;
            }
            int mode;
            try
            {
                int nTemplateGrade = billOcr.GetTemplateGrade(m_strUsMod.Text, out mode);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "识别模板错误" + ex.Message);
                Thread.Sleep(1000);
                nCells = -1;
                nType = -1;
                return recode;
            }
            char[] cArrFieldName = new char[256];
            cArrFieldName.Initialize();
            int nFiledName = -1;
            try
            {
                nFiledName = billOcr.GetFieldNameEx(cArrFieldName);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "识别模板错误" + ex.Message);
                Thread.Sleep(1000);
                nCells = -1;
                nType = -1;
                return recode;
            }
            string temp = "";
            if (nFiledName == 0)
            {
                string strFieldName = new string(cArrFieldName);
                temp = strFieldName;
            }
            try
            {
                recode = billOcr.RecognizeForm(out nCells, out nType);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "RF识别错误" + ex.Message);
                Thread.Sleep(1000);
                nCells = -1;
                nType = -1;
                return recode;
            }
            return recode;
        }
        //解析模板
        private string GetRecogResult(int ncells)
        {
            AutomationBillOcr billOcr = new AutomationBillOcr();
            string strResult = "";
            if (ncells <= 0)
            {
                return strResult;
            }
            List<string> FieldNameList = new List<string>();
            List<string> FieldResultList = new List<string>();
            int i = 0;
            int nbufferlen = 0;
            int nFontTye = -1;
            string tpresult = "";
            string tpname = "";
            for (i = 0; i < ncells; i++)
            {
                tpresult = "";
                tpname = "";
                try
                {
                    billOcr.GetFieldName(i, null, out nbufferlen);
                    char[] lpname = new char[nbufferlen];
                    lpname.Initialize();
                    billOcr.GetFieldName(i, lpname, out nbufferlen);
                    tpname = new string(lpname);
                    FieldNameList.Add(tpname);
                    nbufferlen = 0;
                    billOcr.GetRecognizeResult(i, null, out nbufferlen);
                    char[] lpresult = new char[nbufferlen];
                    lpresult.Initialize();
                    billOcr.GetRecognizeResult(i, lpresult, out nbufferlen);
                    tpresult = new string(lpresult);
                    nFontTye = -1;
                    billOcr.GetCellType(i, out nFontTye);
                    if (nFontTye == 33)
                    {
                        tpresult.Replace("§", "\r\n");
                    }
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "解析错误" + ex.Message);
                    Thread.Sleep(1000);
                    return "";
                }
                if (tpname == "票据类型")
                    if (tpresult == "1" || tpresult == "6")
                        tpresult = "普票";
                    else
                        tpresult = "专票";
                FieldResultList.Add(tpresult);
            }
            int safeCount = Math.Min(FieldNameList.Count, FieldResultList.Count);
            for (i = 0; i < safeCount; i++)
            {
                strResult += FieldNameList[i] + ":" + FieldResultList[i] + "\r\n";
            }
            FieldNameList.Clear();
            FieldResultList.Clear();
            return strResult;
        }
        private HighSpeedRailTicket chuliGTBillTable(string tpresult, string imgUrl)
        {
            HighSpeedRailTicket bpm = new HighSpeedRailTicket();
            List<HighSpeedRailTicket> itbmxlist = new List<HighSpeedRailTicket>();
            if (tpresult != null && tpresult != "")
            {
                string[] infoarryt = tpresult.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None);//根据换行符进
                infoarryt = infoarryt.Where(s => !string.IsNullOrEmpty(s)).ToArray();
                bpm.imgUrl = PiaoJuUploadeAddress;

                if (infoarryt.Length == 11 || infoarryt.Length == 10)
                {
                    if (infoarryt[0].Split(':')[0] == "车次")
                    {
                        bpm.trainNumber = infoarryt[0].Split(':')[1];
                    }
                    if (infoarryt[1].Split(':')[0] == "出发站")
                    {
                        bpm.startStation = infoarryt[1].Split(':')[1];
                    }
                    if (infoarryt[2].Split(':')[0] == "终点站")
                    {
                        bpm.endStation = infoarryt[2].Split(':')[1];
                    }
                    if (infoarryt[3].Split(':')[0] == "日期")
                    {
                        bpm.startDate = infoarryt[3].Split(':')[1];
                    }
                    if (infoarryt[4].Split(':')[0] == "时间")
                    {
                      
                        if (infoarryt[4].Split(':').Length > 2) {
                            bpm.startTime = infoarryt[4].Split(':')[1] + ":" + infoarryt[4].Split(':')[2];
                        } else {
                            bpm.startTime = infoarryt[4].Split(':')[1];
                        }
                    }
                    if (infoarryt[5].Split(':')[0] == "座位")
                    {
                        bpm.seat = infoarryt[5].Split(':')[1];
                    }
                    if (infoarryt[6].Split(':')[0] == "座位类型")
                    {
                        bpm.searType = infoarryt[6].Split(':')[1];

                    }
                    if (infoarryt[7].Split(':')[0] == "票价")
                    {
                        bpm.ticketPrice = infoarryt[7].Split(':')[1];
                    }
                    if (infoarryt[8].Split(':')[0] == "证件号码")
                    {
                        bpm.idNumber = infoarryt[8].Split(':')[1];
                    }
                    if (infoarryt[9].Split(':')[0] == "姓名")
                    {
                        bpm.name = infoarryt[9].Split(':')[1];
                    }
                    if (infoarryt[10].Split(':')[0] == "编号")
                    {
                        bpm.number = infoarryt[10].Split(':')[1];
                    }

                }
            }
            return bpm;
        }

        private string[] gettableHead(string[] tableAll)
        {
            List<string> moneylie = new List<string>();
            List<string> taxmoneylie = new List<string>();
            string temptjje = "";
            for (int i = 0; i < tableAll.Length; i++)
            {
                string[] lie = tableAll[i].Split('|');
                temptjje = "";
                foreach (string zi in lie)
                {
                    if (zi.Trim() != "")
                    {
                        if (zi.Split(':')[0] == "项目名称")
                        {
                            if (zi.Split(':').Length == 2)
                            {
                                if (zi.Split(':')[1].Contains("销售") || zi.Split(':')[1].Contains("际销售") || zi.Split(':')[1].Contains("售"))
                                {
                                    temptjje = "je";
                                }
                                else if (zi.Split(':')[1].Contains("销项税") || zi.Split(':')[1].Contains("实际销项") || zi.Split(':')[1].Contains("际销项"))
                                {
                                    temptjje = "se";
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        if (zi.Split(':').Length == 1)
                        {
                            if (temptjje == "je")
                            {
                                moneylie.Add(zi);
                            }
                            else if (temptjje == "se")
                            {
                                taxmoneylie.Add(zi);
                            }
                        }
                    }

                }
            }
            string[] taxlvlist = new string[moneylie.Count];
            if (moneylie.Count > 0 && taxmoneylie.Count > 0)
            {
                if (moneylie.Count == taxmoneylie.Count)
                {
                    for (int j = 0; j < moneylie.Count; j++)
                    {
                        decimal money = Convert.ToDecimal(moneylie[j]);
                        decimal taxmoney = Convert.ToDecimal(taxmoneylie[j]);
                        string sl = Convert.ToString(Math.Round((taxmoney != 0 ? taxmoney : 10) / (money != 0 ? money : 10), 2) * 100);
                        string taxlv = InvoiceOcrTool.setTaxLv(Convert.ToDecimal(sl));
                        taxlvlist[j] = taxlv;
                    }
                }
            }
            return taxlvlist;
        }

        private static void settjtablevalue(InvoiceOcrTaxtjtableMx itjm, string name, string value)
        {
            if (name == "项目名称")
            {
                itjm.tjprojectName = value;
            }
            else if (name == "合计")
            {
                itjm.tjheji = value;
            }
            else if (name == "17%")
            {
                itjm.seventeenPercent = value;
            }
            else if (name == "16%")
            {
                itjm.sixteenPercent = value;
            }
            else if (name == "13%")
            {
                itjm.threePercent = value;
            }
            else if (name == "10%")
            {
                itjm.tenPercent = value;
            }
            else if (name == "6%")
            {
                itjm.sixPercent = value;
            }
            else if (name == "4%")
            {
                itjm.fourPercent = value;
            }
            else if (name == "3%")
            {
                itjm.threePercent = value;
            }
            else
            {
                itjm.qita = value;
            }
        }

        private static string getBaiFenB(string tablhead)
        {
            string percent = "";
            if (tablhead == "3%")
            {
                percent = "3%";

            }
            else if (tablhead == "4%")
            {
                percent = "4%";
            }
            else if (tablhead == "6%")
            {
                percent = "6%";
            }
            else if (tablhead == "10%")
            {
                percent = "10%";
            }
            else if (tablhead == "13%")
            {
                percent = "13%";
            }
            else if (tablhead == "16%")
            {
                percent = "16%";
            }
            else if (tablhead == "17%")
            {
                percent = "17%";
            }
            return percent;
        }


        //处理总体数据传入服务器
        private InvoiiceOcrModel chuliModelOne(string tpresult, string fileUrl,string qrCodeValue, int recoded, int mubantype, List<InvoiceSonModel> biduilist, List<invoiceOcrDetailedModel> iodMList)
        {
            string apiurl = "";
            //        tpresult.Remove('\\0');
            if (tpresult != null && tpresult != "")
            {
                InvoiiceOcrModel bpm = new InvoiiceOcrModel();
                string[] infoarryt = tpresult.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None);//根据换行符进
                infoarryt = infoarryt.Where(s => !string.IsNullOrEmpty(s)).ToArray();
                //处理数据
                try
                {
                    bpm = chuliModel(infoarryt, out apiurl, fileUrl, tpresult, qrCodeValue,mubantype, biduilist, iodMList);
                    return bpm;
                }
                catch (Exception ex)
                {
                    WsdLogger.yxlog("error", "处理数据错误：" + ex.Message + "图片地址：" + fileUrl);
                    return null;
                }
            }
            else
            {
                string infoessmage;
                char[] erroBuffer = new char[256];
                int nErroLength;
                InvoiiceOcrModel bpm = new InvoiiceOcrModel();
                billOcr.GetErroInformation(recoded, erroBuffer, out nErroLength);
                string urlimg = "";
                string urlbathtime = "";
                string errInfo = new string(erroBuffer);
                infoessmage = errInfo;
                urlimg = fileUrl;
                urlbathtime = fileUrl;
                if (urlbathtime != "")
                {
                    bpm = chuliFeiQi(infoessmage, urlimg, fileUrl);
                    apiurl = ApiUrlList.DATALL;
                }
                return bpm;
            }
        }
        //处理废弃数据
        private InvoiiceOcrModel chuliFeiQi(string infoessmage, string pcnum, string imgurl)
        {
            InvoiiceOcrModel bpm = new InvoiiceOcrModel();
            bpm.stateDesc = infoessmage;
            bpm.declaredate = DeclareDateTool.currentDeclareDae;
            bpm.stateDesc = "废弃";
            bpm.billtype = ModelEnum.FAIL;
            bpm.billtypeDesc = "失败";
            bpm.isloading = "0";
            bpm.state = ModelEnum.FAIL;
            string pc = "";
            bpm.imgUrl = PiaoJuUploadeAddress;
            if (imgurl.Split('_').Length >= 2)
            {
                pc = imgurl.Split('_')[1];
            }
            if (pc != "")
            {
                bpm.batchtime = pc;
            }
            return bpm;
        }
        //处理需要传入的数据封装
        private InvoiiceOcrModel chuliModel(string[] infoarryt, out string apiurl, string fileUrl, string tpresult, string qrCodeValue,int mubantype, List<InvoiceSonModel> biduilist, List<invoiceOcrDetailedModel> iodMList)
        {

            InvoiiceOcrModel bpm = new InvoiiceOcrModel();
            InvoiiceOcrModel bpm2 = new InvoiiceOcrModel();
            InvoiceSonModel ism = new InvoiceSonModel();
            InvoiceSonModel ism2 = new InvoiceSonModel();
            InvoiceSonModel tempisml = new InvoiceSonModel();
            string urlimg = "";
            apiurl = "api/invoiceocr/info";
            bpm = new InvoiiceOcrModel();
            bpm.imgUrl = PiaoJuUploadeAddress;
            urlimg = fileUrl;
            string pc = "";
            if (urlimg.Split('_').Length >= 2)
            {
                pc = urlimg.Split('_')[1];
            }

            if (pc != "")
            {
                bpm.batchtime = pc;
            }
            bpm.stateDesc = "未启用";
            if (mubantype == -1)
            {
                bpm.billtype = ModelEnum.FAIL;//失败
            }
            else
            {
                if (mubantype == 6)
                {
                    bpm.billtype = 3;//单据类型
                }
                else
                {
                    bpm.billtype = mubantype;//单据类型
                }

            }
            bpm.isloading = "0";
            bpm.state = 0;
            string billtypeDesc = ModelEnum.getBillType(mubantype);
            bpm.billtypeDesc = billtypeDesc;
            if (infoarryt[0].Split(':')[0] == "公司名称")
            {
                bpm.tianxiedate = infoarryt[3].Split(':')[1];
                bpm.billtypeDesc = "工资单模板类型";
                bpm.billtype = ModelEnum.CUSTOM;
            }
            bpm.declaredate = DeclareDateTool.currentDeclareDae;
            bpm.invoiceinfoall = tpresult;
            bpm.invoiceOcrSonLists = new List<InvoiceSonModel>();
            int chulinum = 0;
            try
            {
                for (int i = 0; i < infoarryt.Length; i++)
                {
                    chulinum++;
                    try
                    {
                        string Key = "";
                        string Value = "";
                        string[] temp = infoarryt[i].Split(':');
                        if (temp.Length >= 2)
                        {
                            Key = temp[0];
                            Value = temp[1];
                        }
                        if (Key == "发票代码")
                        {
                            ism.invoiceCode = Value;
                        }
                        if (Key == "发票号码")
                        {
                            ism.invoiceNum = Value;
                            bpm.invoiceNum = Value;
                        }
                        if (Key == "开票日期")
                        {
                            ism.invoiceDate = Value;
                            bpm.billingDate = Value;
                        }
                        if (Key == "购方企业名称")
                        {
                            ism.gfcompanyname = Value;
                            if (Value != null && Value != "")
                            {
                                companyNameDB = Value;
                            }
                        }
                        if (Key == "购方纳税号")
                        {
                            ism.gftaxnumber = Value;
                            try
                            {
                                bool biaoshi = WhetherDaiKai(infoarryt);
                                gfchuliData(Value, companyNameDB, biduilist, biaoshi);//的购买方综合
                                tempisml = new InvoiceSonModel();
                            }
                            catch (Exception ex)
                            {
                                WsdLogger.yxlog("error", "筛选OCR公司税号报错" + ex.Message);
                            }
                        }
                        if (Key == "销方企业名称")
                        {
                            ism.xfcompanyname = Value;
                            companyNameDB = Value;
                        }
                        if (Key == "销方纳税号")
                        {
                            ism.xftaxnumber = Value;
                            bool biaoshi = WhetherDaiKai(infoarryt);
                            if (biaoshi)
                            {
                                tempisml.xftaxnumber = Value;
                                try
                                {
                                    gfchuliData(Value, companyNameDB, biduilist, true);//的销买方综合
                                }
                                catch (Exception ex)
                                {
                                    WsdLogger.yxlog("error", "筛选OCR公司税号报错" + ex.Message);
                                }
                            }
                        }
                        if (Key == "价税合计")
                        {
                            ism.totalMoney = Value;
                        }
                        if (Key == "金额")
                        {
                            ism.moneyAmounts = Value;
                        }
                        if (Key == "税额")
                        {
                            ism.taxAmounts = Value;
                        }
                        if (Key == "二维码")
                        {
                            ism.qrCode = Value;
                            if (string.IsNullOrEmpty(Value))
                            {
                                if (!string.IsNullOrEmpty(qrCodeValue)) {
                                    Value = qrCodeValue;
                                }
                            }
                            if (Value != "" && Value != null)
                            {
                                string[] QRcodeInfo = Value.Split(',');
                                if (QRcodeInfo.Count() > 5)
                                {
                                    ism.moneyAmounts = QRcodeInfo[4];
                                    string typenum = QRcodeInfo[1];
                                    if (typenum == "01")
                                    {
                                        ism.invoicetype = "专票";
                                    }
                                    if (typenum == "04" || typenum == "10")
                                    {
                                        ism.invoicetype = "普票";
                                    }
                                    ism.moneyAmountsState = CompanyOrMoneyStateEnum.InvoiceMoneyHaveQRcodeInfo;
                                    string year = QRcodeInfo[5].Substring(0, 4);
                                    string month = QRcodeInfo[5].Substring(4, 2);
                                    string day = QRcodeInfo[5].Substring(6, 2);
                                    string QRdate = year + "-" + month + "-" + day;
                                    ism.invoiceDate = QRdate;
                                    bpm.billingDate = QRdate;
                                    ism.invoiceNum = QRcodeInfo[3];
                                    bpm.invoiceNum = QRcodeInfo[3];
                                }
                            }
                        }
                        if (Key == "密码区")
                        {
                            ism.passwordpage = Value;
                        }
                        if (Key == "价税合计大写")
                        {
                            ism.moneytaxhjMax = Value;
                        }
                        if (Key == "&明细&")
                        {
                            if (Value != null && Value != "")
                            {
                                ism.detailed = Value;
                            }
                            else
                            {
                                ism.detailed = null;
                            }
                            try
                            {
                                iodMList = getMingXi(Value, iodMList);
                            }
                            catch (Exception ex)
                            {
                                WsdLogger.yxlog("error", "明细处理报错" + ex.Message);
                            }
                        }
                        if (Key == "备注")
                        {
                            ism.remarks = Value;
                        }
                        if (Key == "税率")
                        {
                            ism.taxRate = Value;
                        }
                        if (Key == "校验码")
                        {
                            ism.checkcode = Value;
                        }
                        if (Key == "票据类型")
                        {
                            if (string.IsNullOrEmpty(ism.invoicetype) || string.IsNullOrEmpty(ism.qrCode))
                            {
                                ism.invoicetype = Value;
                            }
                        }
                        if (Key == "购买方地址及电话")
                        {
                            ism.gfaddressTelephone = Value;
                        }
                        if (Key == "购买方开户行及账号")
                        {
                            ism.gfbankAccount = Value;
                        }
                        if (Key == "销售方地址及电话")
                        {
                            ism.xfaddressTelephone = Value;
                        }
                        if (Key == "销售方开户行及账号")
                        {
                            ism.xfbankAccount = Value;
                        }
                        if (Key == "收款人")
                        {
                            ism.skMan = Value;
                        }
                        if (Key == "复核")
                        {
                            ism.checkeds = Value;
                        }
                        if (Key == "开票人")
                        {
                            ism.kpMan = Value;
                        }
                        if (Key == "联数")
                        {
                            ism.lianshu = Value;
                        }
                        if (Key == "印刷发票代码")
                        {
                            ism.ysinvoiceCode = Value;
                        }
                        if (Key == "印刷发票号码")
                        {
                            ism.ysinvoiceNum = Value;
                        }
                        if (Key == "开票标识")
                        {
                            ism.invoiceMark = Value;
                        }
                        if (Key == "二维码发票号码")
                        {
                            if (Value != null && Value != "")
                            {
                                ism.invoiceNum = Value;
                                bpm.invoiceNum = Value;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WsdLogger.yxlog("error", "第" + chulinum + "条解析数据错误" + ex.Message);
                        continue;
                    }

                }
                ism.invoiceState = "0";
                bpm.invoiceOcrDetailedDtoList = iodMList;
                bpm.invoiceOcrSonLists.Add(ism);
            }
            catch (Exception ex)
            {
                WsdLogger.yxlog("error", "解析子表数据报错" + ex.Message);
            }


            return bpm;
        }


        private void gfchuliData(string Value, string compNameDB, List<InvoiceSonModel> biduilist, bool biaoshi)
        {
            int tempgf = 0;
            if (Value != null && Value != "" || compNameDB != null && compNameDB != "")
            {
                if (compNameDB.Length > 3)
                {
                    if (biduilist.Count > 0)
                    {
                        for (int i = 0; i < biduilist.Count; i++)
                        {
                            try
                            {
                                int xiangsi = 0;
                                string value = "X";
                                string number = "Y";
                                if (Value.Length > biduilist[i].gftaxnumber.Length)
                                {

                                    xiangsi = InvoiceOcrTool.getTaxNum(Value, biduilist[i].gftaxnumber);
                                }
                                else
                                {
                                    xiangsi = InvoiceOcrTool.getTaxNum(biduilist[i].gftaxnumber, Value);
                                }
                                int namexiangsi = InvoiceOcrTool.NameXianSiD(compNameDB, biduilist[i].gfcompanyname.Replace("公司", ""));
                                if (Value.Length >= 4)
                                {
                                    value = Value.Substring(Value.Length - 4, 4);
                                }
                                if (biduilist[i].gftaxnumber.Length > 4)
                                {
                                    number = biduilist[i].gftaxnumber.Substring(biduilist[i].gftaxnumber.Length - 4, 4);
                                }
                                if (Value != null && Value != "")
                                {
                                    if (Convert.ToString(biduilist[i].gftaxnumber) == Convert.ToString(Value))
                                    {
                                        try
                                        {
                                            tempgf++;
                                            biduilist[i].gfbankAccount = (int.Parse(biduilist[i].gfbankAccount) + 1) + "";
                                        }
                                        catch (Exception ex)
                                        {
                                            WsdLogger.yxlog("error", "算法错误" + ex.Message);
                                        }
                                    }
                                    else if (Convert.ToString(biduilist[i].gfcompanyname) == compNameDB)
                                    {
                                        try
                                        {
                                            tempgf++;
                                            biduilist[i].gfbankAccount = (int.Parse(biduilist[i].gfbankAccount) + 1) + "";
                                        }
                                        catch (Exception ex)
                                        {
                                            WsdLogger.yxlog("error", "算法错误" + ex.Message);
                                        }
                                    }
                                    else if (xiangsi > (biduilist[i].gftaxnumber.Length - 3 > 0 ? biduilist[i].gftaxnumber.Length - 3 : 0))
                                    {
                                        try
                                        {
                                            tempgf++;
                                            biduilist[i].gfbankAccount = (int.Parse(biduilist[i].gfbankAccount) + 1) + "";
                                        }
                                        catch (Exception ex)
                                        {
                                            WsdLogger.yxlog("error", "算法错误" + ex.Message);
                                        }
                                    }
                                    //else if (value == number)
                                    //{
                                    //    try
                                    //    {
                                    //        tempgf++;
                                    //        biduilist[i].gfbankAccount = (int.Parse(biduilist[i].gfbankAccount) + 1) + "";
                                    //    }
                                    //    catch (Exception ex)
                                    //    {
                                    //        WsdLogger.yxlog("error", "算法错误" + ex.Message);
                                    //    }
                                    //}
                                    else
                                    {
                                        int comnum = 1000;
                                        if (compNameDB.Length < 6)
                                        {
                                            comnum = 3;
                                        }
                                        else if (compNameDB.Length >= 6 && compNameDB.Length < 9)
                                        {
                                            comnum = 5;
                                        }
                                        else if (compNameDB.Length >= 9)
                                        {
                                            comnum = 7;
                                        }
                                        if (namexiangsi >= comnum)
                                        {
                                            try
                                            {
                                                tempgf++;
                                                biduilist[i].gfbankAccount = (int.Parse(biduilist[i].gfbankAccount) + 1) + "";
                                                if (compNameDB.Length > biduilist[i].gfcompanyname.Length)
                                                {
                                                    biduilist[i].gfcompanyname = compNameDB;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                WsdLogger.yxlog("error", "算法错误" + ex.Message);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                WsdLogger.yxlog("error", "算法处理错误" + ex.Message);
                                continue;
                            }
                        }

                        if (tempgf == 0)
                        {
                            InvoiceSonModel tempisml = new InvoiceSonModel();
                            tempisml.gftaxnumber = Value;
                            tempisml.gfbankAccount = "1";
                            tempisml.gfcompanyname = compNameDB;
                            if (biaoshi)
                            {
                                tempisml.invoiceMark = "NO";
                            }
                            else
                            {
                                tempisml.invoiceMark = "DK";
                            }

                            biduilist.Add(tempisml);
                        }
                    }
                    else
                    {
                        InvoiceSonModel tempisml = new InvoiceSonModel();
                        tempisml.gftaxnumber = Value;
                        tempisml.gfbankAccount = "1";
                        tempisml.gfcompanyname = compNameDB;
                        if (biaoshi)
                        {
                            tempisml.invoiceMark = "NO";
                        }
                        else
                        {
                            tempisml.invoiceMark = "DK";
                        }
                        biduilist.Add(tempisml);
                    }
                }

            }


        }


        private bool WhetherDaiKai(string[] infoarryt)
        {
            string biaoshi = "";
            for (int j = 0; j < infoarryt.Length; j++)
            {
                string tempKey = "";
                string tempValue = "";
                string[] tempp = infoarryt[j].Split(':');
                if (tempp.Length >= 2)
                {
                    tempKey = tempp[0];
                    tempValue = tempp[1];
                }
                if (tempKey == "开票标识")
                {
                    if (tempValue != "代开")
                    {
                        biaoshi = "Y";
                        break;
                    }
                }
            }
            if (biaoshi == "Y")
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        //处理明细数据
        private List<invoiceOcrDetailedModel> getMingXi(string Value, List<invoiceOcrDetailedModel> iodMList)
        {
            string neirongs = "";
            string moneymx = "";
            string taxlvmx = "";
            string taxmoneymx = "";
            string number = "";
            string danj = "";
            int chulimingi = 0;
            iodMList = new List<invoiceOcrDetailedModel>();
            invoiceOcrDetailedModel dc = new invoiceOcrDetailedModel();
            int detaildejs = 0;
            if (Value != null)
            {
                var deataileds = Value.Split('§');
                for (var k = 0; k < deataileds.Length; k++)
                {
                    chulimingi++;
                    try
                    {
                        if (deataileds[k] != "" && deataileds[k] != null)
                        {
                            var deatailedsas = deataileds[k].Split('#');
                            for (var y = 0; y < deatailedsas.Length; y++)
                            {
                                if (deatailedsas[y].IndexOf("应税劳务") != -1)
                                {
                                    neirongs = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (deatailedsas[y].IndexOf("数量") != -1)
                                {
                                    number = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (deatailedsas[y].IndexOf("单价") != -1)
                                {
                                    danj = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (deatailedsas[y].IndexOf("金额") != -1)
                                {
                                    moneymx = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (deatailedsas[y].IndexOf("税额") != -1)
                                {
                                    taxmoneymx = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (deatailedsas[y].IndexOf("税率") != -1)
                                {
                                    taxlvmx = deatailedsas[y].Split('=')[1].Replace("&", "");
                                    detaildejs++;
                                }
                                if (detaildejs == 6)
                                {
                                    dc = new invoiceOcrDetailedModel();
                                    dc.productName = neirongs;
                                    dc.moneyAmount = moneymx;
                                    dc.detaileTaxRate = taxlvmx;
                                    dc.taxAmount = taxmoneymx;
                                    dc.unitPrice = danj;
                                    dc.mxNumber = number;
                                    iodMList.Add(dc);
                                    detaildejs = 0;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        WsdLogger.yxlog("error", "第" + chulimingi + "条处理明细错误" + ex.Message);
                        continue;
                    }

                }
            }
            return iodMList;
        }







        //传入服务器统计表保存
        private void forwardingToserversetj(List<HighSpeedRailTicket> bpm, string apiurl)
        {
            string tpresult;
            string result = "";
            try
            {
                result = RestOrcTool.postHighSpeedRailTicket(out tpresult, bpm, apiurl);
                //ocrlog.Write("批量上传服务器返回信息：" + result);
                // WsdLogger.yxlog("error", "批量上传服务器返回信息" + result);
            }
            catch (Exception es)
            {
                WsdLogger.yxlog("error", "传服务器错误" + es.Message);
                return;
            }
        }



        //获取模板文件路径集合
        private List<string> OnLoad()
        {
            List<string> mbPathList = new List<string>();
            //获取指定文件夹的所有文件
            var url = AppDomain.CurrentDomain.BaseDirectory;
            string newPath = Path.Combine(url, "mod");
            string[] paths = Directory.GetFiles(newPath);
            foreach (var item in paths)
            {
                //获取文件后缀名
                string extension = Path.GetExtension(item).ToLower();
                if (extension == ".mod")
                {
                    mbPathList.Add(item);//添加到模板list中
                }
            }
            return mbPathList;
        }

    }
}